package io.renren.modules.wyzsphone.controller;


import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import io.renren.common.utils.R;
import io.renren.modules.wyzs.entity.FactoryInfo;
import io.renren.modules.wyzs.service.FactoryService;
import io.renren.modules.wyzsphone.commWithWCF.*;
import io.renren.modules.wyzsphone.entity.FactoryUser;
import io.renren.modules.wyzsphone.service.FactoryUserService;
import io.renren.modules.wyzsphone.utils.Constant;
import io.renren.modules.wyzsphone.utils.Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Date;
import java.text.SimpleDateFormat;


@RestController
@RequestMapping("/factoryUser")
public class FactoryUserController {

    @Autowired
    FactoryUserService factoryUserService;
    @Autowired
    FactoryService factoryService;

    /**
     * 验证工厂用户
     */
    @RequestMapping("/BindingFactoryUser")
    public R bindingFactoryUser(@RequestBody String jsonStr) throws Exception {




        Gson _gson = new Gson();
       Map<String,Object> params = Utils.JsonToMap(jsonStr);

        FactoryInfo factoryInfo=factoryService.getFactoryById((String) params.get("factoryId"));
        if(factoryInfo!=null) {
            params.put("URL",factoryInfo.getFactoryURL());
            XModeRtn ValueRtn = BindingFactoryUser(params);
            Object uid = ValueRtn.getData().getData("uid");
            if (uid != null) {
                params.put("factoryName", factoryInfo.getFactoryname());
                params.put("factoryId", factoryInfo.getId());
                params.put("uid", uid);
//                FactoryUser f=factoryUserService.getUserByFactoryId(params);
//                if(f!=null){
//
//                    return R.error("这个账户已绑定过，请先解绑");
//
//                }

                factoryUserService.saveFactoryUser(params);

//                FactoryUser factoryUser=new FactoryUser();
//                factoryUser.setFactoryId(factoryInfo.getId());
//                factoryUser.setUid((String) uid);
//                factoryUser.setFactoryName(factoryInfo.getFactoryname());
//                return R.ok().put("data",factoryUser);
            }
            //获得SIP 返回的执行正确或错误的提示信息
            //DataItem di=ValueRtn.getData();
            String stat =(String)ValueRtn.getData().getData("state");
            String  msg = (String)ValueRtn.getData().getData("message");
            //JsonObject数据为空时return maps2
            Map<String, Object> maps2 = _gson.fromJson(ValueRtn.getMessage(), new TypeToken<Map<String, Object>>(){}.getType());
            maps2.put("state",stat);
            maps2.put("msg",maps2.get("Message")+ msg);
            //正常返回Json数据 return maps
            Map<String, Object> maps = _gson.fromJson(ValueRtn.getJsonObject(), new TypeToken<Map<String, Object>>() {}.getType());
            //maps.put("state",ValueRtn.getState());
            if(maps!=null) {
                maps.put("state", stat);
                maps.put("msg", maps2.get("Message")+msg);

                for (Map.Entry<String, Object> entry : maps.entrySet()) {
                    System.out.println("key: " + entry.getKey() + "  " + "value: " + entry.getValue());
                }
                return R.ok().put("data",maps);
            }



            for (Map.Entry<String, Object> entry : maps2.entrySet()) {
                System.out.println("key: " + entry.getKey() + "  " + "value: " + entry.getValue());

            }
            return R.ok().put("data",maps2);
//            } else
//                return R.error(ValueRtn.getMessage());
        }
        else return R.error("工厂不存在");
    }


    /*
    修改用户密码
   */
    @RequestMapping("/ChangeFactoryUserPassword")
    public R changeFactoryUserPassword(@RequestBody String jsonStr) throws Exception{

        Map<String,Object> params = Utils.JsonToMap(jsonStr);
        Gson _gson = new Gson();
        FactoryInfo factoryInfo= factoryService.getFactoryById((String) params.get("factoryId"));
        if(factoryInfo!= null){
            params.put("URL",factoryInfo.getFactoryURL());
            XModeRtn ValueRtn = ChangeFactoryUserPass(params);
//            Object uid = ValueRtn.getData().getData("uid");
//            if (uid != null) {
//                params.put("factoryName",factoryInfo.getFactoryname());
//                params.put("factoryId",factoryInfo.getId());
//                params.put("uid",uid);
//                factoryUserService.changeFactoryUserPass(params);
//                FactoryUser factoryUser=new FactoryUser();
//                factoryUser.setFactoryId(factoryInfo.getId());
//                factoryUser.setUid((String) uid);
//                factoryUser.setFactoryName(factoryInfo.getFactoryname());
//                return R.ok().put("data",factoryUser);
//            } else
//                return R.error(ValueRtn.getMessage());
            //Map<String, Object> maps = new HashMap<String, Object>();
            Object state = ValueRtn.getData().getData("state");

            if(state!=null) {
                //maps.put("state", ValueRtn.getData().getData("state"));
                //maps.put("msg",ValueRtn.getData().getData("message"));

                if ("ok".equals((String) state)) {

                    params.put("factoryName", factoryInfo.getFactoryname());
                    params.put("factoryId", factoryInfo.getId());
                    params.put("password",params.get("passwordnew"));
                    //params.put("uid", uid);
                    factoryUserService.changeFactoryUserPass(params);

                    //FactoryUser factoryUser = new FactoryUser();
                    //factoryUser.setFactoryId(factoryInfo.getId());
                    //factoryUser.setUid((String) uid);
                    //factoryUser.setFactoryName(factoryInfo.getFactoryname());

                    //return R.ok().put("data", maps);

                }
            }

            //获得SIP 返回的执行正确或错误的提示信息
            DataItem di=ValueRtn.getData();
            String stat =(String)di.getData("state");


            Map<String, Object> maps2 = _gson.fromJson(ValueRtn.getMessage(), new TypeToken<Map<String, Object>>(){}.getType());
            maps2.put("state",stat);
            maps2.put("msg",maps2.get("Message"));



            for (Map.Entry<String, Object> entry : maps2.entrySet()) {
                System.out.println("key: " + entry.getKey() + "  " + "value: " + entry.getValue());

            }
            return R.ok().put("data", maps2);




           // return R.error("修改失败");

        }
        else return R.error("工厂不存在");
    }





    @RequestMapping("/getFactoryList")
    public R getMyFactoryList()
    {
        List<FactoryUser> configList = factoryUserService.getMyFactoryList();
        return R.ok().put("data", configList);
    }

    /**
     * 解绑工厂用户
     */
    @RequestMapping("/deleteFactoryUser")
    public R deleteFactoryUser(@RequestBody String factoryId)
    {
        Map mapFactoryId=Utils.JsonToMap(factoryId);
        factoryUserService.deleteFactoryUser((String) mapFactoryId.get("factoryId"));
        return R.ok();
    }


//    @RequestMapping("/loginFacotry")
//    public R loginFacotry(@RequestBody String factoryId) throws Exception {
//        Map mapFactoryId=Utils.JsonToMap(factoryId);
//        FactoryUser factoryUser = factoryUserService.getMyFactoryById((String) mapFactoryId.get("factoryId"));
//        String password= CommonEncryptUtil.aesDecrypt(factoryUser.getPassword(), Constant.SALT);
//        Map<String,Object> map=new HashMap<>();
//        map.put("facotryUsername",factoryUser.getFacotryUsername());
//        map.put("password",password);
//        map.put("URL",factoryUser.getFactoryURL());
//        Map ValueRtn = BindingFactoryUser1(map);
//        return R.ok().put("data", ValueRtn);
//    }


    @RequestMapping("/loginFacotry")
    public R loginFacotry(@RequestBody String jsonStr) throws Exception {
        Map<String,Object> params=Utils.JsonToMap(jsonStr);
        FactoryUser factoryUser = factoryUserService.getMyFactoryById((String) params.get("factoryId"));

        FactoryInfo factoryInfo=factoryService.getFactoryById((String) params.get("factoryId"));

        String password= CommonEncryptUtil.aesDecrypt(factoryUser.getPassword(), Constant.SALT);
        Map<String,Object> map=new HashMap<>();
        map.put("facotryUsername",factoryUser.getFacotryUsername());
        map.put("password",password);
        map.put("URL",factoryUser.getFactoryURL());
        map.put("imei",params.get("imei"));//zcx
        Map ValueRtn = BindingFactoryUser1(map);

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        //记录登录信息
        Object uid = ValueRtn.get("UID");
        if (uid != null) {

            params.put("factoryName", factoryInfo.getFactoryname());
            params.put("factoryId", factoryInfo.getId());
            params.put("factoryUsername", factoryUser.getFacotryUsername());
            params.put("uid", uid);
            params.put("username",factoryUser.getUsername());
            params.put("loginTime",df.format(new Date()));

            //factoryUserService.saveFactoryLoginInfo(params);


        }



        return R.ok().put("data", ValueRtn);
    }



    /**
     * 向服务器端发送验证信息
     */
    private XModeRtn BindingFactoryUser(Map<String, Object> params) {

        Gson _gson = new Gson();
        CommWithWCF ser = new CommWithWCF();
        XModeSnd Value = new XModeSnd();
        BillTempGeter billTempGeter=new BillTempGeter();
        String url= (String) params.get("URL");
        Value.setURL(url);
        Value.setFile("M00");
        Value.setMethod("Login");
        Value.getData().setData("username", params.get("facotryUsername"));
        Value.getData().setData("password", params.get("password"));
        Value.getData().setData("imei",  params.get("imei"));
       // Value.getData().setData("imei", "");
        BillTempGeter geter = new BillTempGeter();
        geter.setClassType(billTempGeter.getClassType());
        Value.setJsonObject(_gson.toJson(geter));
        XModeRtn ValueRtn = ser.Code(Value);

        return ValueRtn;
    }

    /**
     * 向服务器端发送修改密码
     */
    private XModeRtn ChangeFactoryUserPass(Map<String,Object> params){

        Gson _gson = new Gson();
        CommWithWCF ser = new CommWithWCF();
        XModeSnd Value = new XModeSnd();
        BillTempGeter billTempGeter=new BillTempGeter();
        String url= (String) params.get("URL");
        Value.setURL(url);
        Value.setFile("M00");
        Value.setMethod("ModifyUserPassword");
        Value.getData().setData("username",params.get("factoryUsername"));
        Value.getData().setData("passwordold",params.get("passwordold"));
        Value.getData().setData("passwordnew",params.get("passwordnew"));

        BillTempGeter geter = new BillTempGeter();
        geter.setClassType(billTempGeter.getClassType());
        Value.setJsonObject(_gson.toJson(geter));
        XModeRtn ValueRtn = ser.Code(Value);
        return ValueRtn;
    }




    /**
     * 向服务器端发送验证信息
     */
    private Map BindingFactoryUser1(Map<String, Object> params) {

        Gson _gson = new Gson();
        CommWithWCF ser = new CommWithWCF();
        XModeSnd Value = new XModeSnd();
        BillTempGeter billTempGeter=new BillTempGeter();
        String url= (String) params.get("URL");
        Value.setURL(url);
        Value.setFile("M00");
        Value.setMethod("Login");
        Value.getData().setData("username", params.get("facotryUsername"));
        Value.getData().setData("password", params.get("password"));
        Value.getData().setData("imei",params.get("imei"));
        BillTempGeter geter = new BillTempGeter();
        geter.setClassType(billTempGeter.getClassType());
        Value.setJsonObject(_gson.toJson(geter));
        XModeRtn ValueRtn = ser.Code(Value);

       //获得SIP 返回的执行正确或错误的提示信息
        DataItem di=ValueRtn.getData();
        String stat =(String)di.getData("state");
        String  msg = (String)di.getData("message");
       //非正常返回Json数据时return maps2
        String rtnmsg = (String)ValueRtn.getMessage();
        //JsonValidator jv = new JsonValidator();
        Map<String ,Object> maps2 = new HashMap<String,Object>();
        if(isJSONValid(rtnmsg)) {
            maps2 = _gson.fromJson(ValueRtn.getMessage(), new TypeToken<Map<String, Object>>() {
            }.getType());
            maps2.put("state",stat);
            maps2.put("msg",maps2.get("Message")+msg);
        }else {
            maps2.put("state", stat);
            maps2.put("msg", rtnmsg );
        }
            //正常返回Json数据 return maps
            Map<String, Object> maps = _gson.fromJson(ValueRtn.getJsonObject(), new TypeToken<Map<String, Object>>() {}.getType());
            //maps.put("state",ValueRtn.getState());
            if(maps!=null) {
                maps.put("state", stat);
                maps.put("msg", maps2.get("Message")+msg);

                for (Map.Entry<String, Object> entry : maps.entrySet()) {
                    System.out.println("key: " + entry.getKey() + "  " + "value: " + entry.getValue());
                }
                return maps;
            }



            for (Map.Entry<String, Object> entry : maps2.entrySet()) {
                System.out.println("key: " + entry.getKey() + "  " + "value: " + entry.getValue());

            }
            return maps2;


    }

    public  boolean isJSONValid(String test) {
        try {
            JSONObject.parseObject(test);
        } catch (JSONException ex) {
            try {
                JSONObject.parseArray(test);
            } catch (JSONException ex1) {
                return false;
            }
        }
        return true;
    }


}
